import { makeAutoObservable, action, observable } from "mobx";
import { DomItem } from "../@types";
import { cloneDeep } from "lodash";

export default class DndStore {

    domItems: DomItem[] = [];

    selectedDomItem: DomItem | null = null;

    constructor() {
        makeAutoObservable(this, {}, { autoBind: true });
    }

    @action
    addItem = (item: DomItem) => {
        if (!item) {
            return;
        }
        this.domItems = [...this.domItems, item];
    }

    @action
    setItems = (items: DomItem[]) => {
        this.domItems = items || [];
    }

    @action
    setSelectedDomItem = (item: DomItem) => {
        this.selectedDomItem = item;
    }

    @action
    updateItem = (item: DomItem) => {
        const copy = cloneDeep(this.domItems);
        const findIndex = copy.findIndex(i => i.id == item.id);
        if (findIndex >= 0) {
            copy.splice(findIndex, 1, item);
            this.domItems = copy;
        } else {
            console.error('未知item', item);
        }
    }
}